from django.shortcuts import render
from django.db import transaction
from decimal import Decimal
from rest_framework.decorators import action
from rest_framework.response import Response
from dvadmin.utils.viewset import CustomModelViewSet
from .models import Material, StockRecord
from .serializers import (
    MaterialSerializer, MaterialCreateUpdateSerializer,
    StockRecordSerializer, StockRecordCreateUpdateSerializer
)

# Create your views here.

class MaterialViewSet(CustomModelViewSet):
    """原材料视图集"""
    queryset = Material.objects.all()
    serializer_class = MaterialSerializer
    create_serializer_class = MaterialCreateUpdateSerializer
    update_serializer_class = MaterialCreateUpdateSerializer

    @action(detail=True, methods=['get'])
    def stock_records(self, request, pk=None):
        """获取指定原材料的库存记录"""
        material = self.get_object()
        records = StockRecord.objects.filter(material=material)
        serializer = StockRecordSerializer(records, many=True)
        return Response(serializer.data)

class StockRecordViewSet(CustomModelViewSet):
    """库存记录视图集"""
    queryset = StockRecord.objects.all()
    serializer_class = StockRecordSerializer
    create_serializer_class = StockRecordCreateUpdateSerializer
    update_serializer_class = StockRecordCreateUpdateSerializer
    
    # 配置导入字段
    import_serializer_class = StockRecordCreateUpdateSerializer
    import_field_dict = {
        "material": {"title": "原材料", "choices": {"queryset": Material.objects.all(), "values_name": "name"}},
        "record_type": {
            "title": "记录类型",
            "choices": {
                "data": {"入库": "in", "出库": "out", "盘点": "check"},
            }
        },
        "quantity": "数量",
        "remark": "备注",
    }
    
    # 配置导出字段
    export_serializer_class = StockRecordSerializer
    export_field_label = {
        "material__name": "原材料",
        "record_type": "记录类型",
        "quantity": "数量",
        "before_quantity": "操作前库存",
        "after_quantity": "操作后库存",
        "remark": "备注",
        "create_datetime": "创建时间",
    }

    @transaction.atomic
    def perform_create(self, serializer):
        """创建库存记录时自动更新原材料库存"""
        material = Material.objects.get(id=self.request.data['material'])
        quantity = Decimal(str(self.request.data['quantity']))  # 转换为Decimal类型
        record_type = self.request.data['record_type']
        
        # 记录操作前库存
        before_quantity = material.current_stock
        
        # 根据记录类型更新库存
        if record_type == 'in':
            material.current_stock += quantity
        elif record_type == 'out':
            if material.current_stock < quantity:
                raise ValueError("库存不足")
            material.current_stock -= quantity
        elif record_type == 'check':
            material.current_stock = quantity
            
        # 保存更新后的库存
        material.save()
        
        # 创建库存记录，自动填充before_quantity和after_quantity
        serializer.save(
            before_quantity=before_quantity,
            after_quantity=material.current_stock
        )
